/**
 * Copyright 2011 Mathieu Magnaudet
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package edu.enac.geoapp.wims;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import edu.enac.geoapp.wims.exception.WimsException;
import edu.enac.geoapp.wims.model.WeatherProduct;


/**
 * Parser for xml files containing Weather Product (WIMS format)
 * 
 * @author mathieu
 * 
 */
public class WimsParser {
	private String pathTofile;
	private XMLReader saxReader;
	private WeatherProduct product;
	private static Logger logger = Logger.getLogger(WimsParser.class);

	public WimsParser() {
		product = null;
	}

	/**
	 * Parses the given file supposed to contain a Weather Product
	 * 
	 * @param path
	 */
	public void parse(String path) throws WimsException {
		this.pathTofile = path;
		try {
			saxReader = XMLReaderFactory
					.createXMLReader("org.apache.xerces.parsers.SAXParser");
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		product = new WeatherProduct();
		parseGenericData();
		parseSpecificData();

	}

	/**
	 * 
	 * @return the WeatherProduct generated from the last parsed file
	 */
	public WeatherProduct getProduct() {
		return product;
	}

	private void parseGenericData() throws WimsException {
		GlobalDataContentHandler handler = new GlobalDataContentHandler(product);
		try {
			saxReader.setContentHandler(handler);
			saxReader.parse(pathTofile);
		} catch (SAXException e) {
			logger.warn(e.getMessage());
		} catch (IOException e) {
			logger.warn(e.getMessage());
		}
	}

	private void parseSpecificData() {
		ProductContentHandler handler = new ProductContentHandler(product);
		try {
			saxReader.setContentHandler(handler);
			saxReader.parse(pathTofile);
		} catch (SAXException e) {
			logger.warn(e.getMessage());
		} catch (IOException e) {
			logger.warn(e.getMessage());
		}
	}
}
